package zookeeper.demo;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

/**
 * @author 明月工作室
 */
public class ZkListener implements Watcher {
    private ZooKeeper zooKeeper;

    public ZkListener(ZooKeeper zooKeeper) {
        this.zooKeeper = zooKeeper;
    }

    @Override
    public void process(WatchedEvent event) {
        if (event.getType() == Event.EventType.NodeDataChanged) {
            try {
                Stat stat = zooKeeper.exists(event.getPath(), false);
                if (stat != null) {
                    byte[] data = zooKeeper.getData(event.getPath(), false, stat);
                    System.out.println("Data changed for path: " + event.getPath() + ", value: " + new String(data));
                } else {
                    System.out.println("Node does not exist: " + event.getPath());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
